const CryptoJS = require('crypto-js');
const Encrypt = require('./jsencrypt.js'); //路径看个人的放哪里哈
const CronParser = require('cron-parser'); // 根据 conditionList 查找定时器，并且解析 cron 表达式
const {logs} = require('@/utils/logs.js');
// 返回 秒 分 时 日 月 星期 年
// conditionType = 1 表示是定时器
import moment from 'moment'
export const parseCron = (conditionList) => {
	let expression = '';
	for (let i = 0; i < conditionList.length; i++) {
		const item = conditionList[i];
		if (item.conditionType === 1) {
			expression = item.conditionValue.cron;
		}
	}
	let fields = {}
	let platform = uni.getSystemInfoSync().osName
	// 0 30 8 ? * 1,2,3,4,5     秒时分 ？* 星期
	let time = expression.split('?')[0].split(' ')
	let week = trimAll(expression.split('*')[1]).split(',')
	let arr = []
	if (platform == 'ios') {
		fields.hour = [Number(time[2])]
		fields.minute = [Number(time[1])]
		fields.second = [Number(time[0])]
		week.forEach((item) => {
			arr.push(Number(item))
		})
		fields.dayOfWeek = arr
	} else {
		let interval = CronParser.parseExpression(expression);
		fields = JSON.parse(JSON.stringify(interval.fields));
	}
	return fields;
};
//去除所有空格
export function trimAll(ele) {
	if (typeof ele === 'string') {
		return ele.split(/[\t\r\f\n\s]*/g).join('');
	} else {
		console.error(`${typeof ele} is not the expected type, but the string type is expected`)
	}
}
// 指定位置清除空格（第二个参数控制位置）1 串的模板 2 清除哪边空格
export function deleSpac(str, direction) {
	if (typeof str !== 'string') { // 限制下条件，必须是字符串
		console.error(`${typeof ele} is not the expected type, but the string type is expected`)
		return false
	}
	let Reg = '';
	switch (direction) {
		case 'left': // 去除左边
			Reg = /^[\t\r\f\n\s]+/g;
			break;
		case 'right': // 去除右边
			Reg = /([\t\r\f\n\s]+)$/g;
			break;
		case 'both': // 去除两边
			Reg = /(^[\t\r\f\n\s]*)|([\t\r\f\n\s]*$)/g
			break;
		default: // 没传默认全部，且为下去除中间空格做铺垫
			Reg = /[\t\r\f\n\s]*/g;
			break;
	}
	let newStr = str.replace(Reg, '');
	if (direction == 'middle') {
		let RegLeft = str.match(/(^[\t\r\f\n\s]*)/g)[0]; // 保存右边空格
		let RegRight = str.match(/([\t\r\f\n\s]*$)/g)[0]; // 保存左边空格
		newStr = RegLeft + newStr + RegRight; // 将空格加给清完全部空格后的字符串
	}
	return newStr;
}
// 格式化时间
export const formatTime = (date) => {
	const year = date.getFullYear();
	const month = date.getMonth() + 1;
	const day = date.getDate();
	const hour = date.getHours();
	const minute = date.getMinutes();
	const second = date.getSeconds();
	return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`;
};
export const formatDate = (date) => {
	const year = date.getFullYear();
	const month = date.getMonth() + 1;
	const day = date.getDate();
	const hour = date.getHours();
	const minute = date.getMinutes();
	const second = date.getSeconds();
	return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute, second].map(formatNumber).join(':')}`;
};

const formatNumber = (n) => {
	n = n.toString();
	return n[1] ? n : `0${n}`;
}; // 转化周（星期）数组为字符串

export const formatWeektoString = (week) => {
	let weekString = '';
	for (let i = 0; i < week.length; i++) {
		const item = week[i];
		switch (item) {
			case 0:
				weekString += '周日 ';
				break;
			case 1:
				weekString += '周一 ';
				break;
			case 2:
				weekString += '周二 ';
				break;
			case 3:
				weekString += '周三 ';
				break;
			case 4:
				weekString += '周四 ';
				break;
			case 5:
				weekString += '周五 ';
				break;
			case 6:
				weekString += '周六 ';
				break;
		}
	}
	return weekString;
};

//device缓存
export function deviceStorage(sn, type, data) {
	let device = uni.getStorageSync(sn);
	device[type] = data;
	uni.setStorageSync(sn,device)
};

//wifi信号转换
export function convertdBm2RSSI(dBm, type, returnType) {
	let level = 0;
	if (dBm < 0 && dBm >= -40) {
		level = 100;
	} else if (dBm < -40 && dBm >= -50) {
		level = (dBm + 90) * 2;
	} else if (dBm < -50 && dBm >= -80) {
		level = dBm + 129;
	} else if (dBm < -80 && dBm >= -85) {
		level = (dBm + 96) * 3;
	} else if (dBm < -85 && dBm > -100) {
		level = (dBm + 100) * 2;
	} else if (dBm <= -100) {
		level = 0;
	}
	if (returnType) {
		return level
	} else {
		return showWifiSignal(level, type)
	}
};

// 显示wifi信号图标1
function showWifiSignal(e, type) {
	e = Math.abs(e)
	let wifiUrl = '';
	let wifiNum = 1;
	if (type == 1 || !type) {
		if (e <= 33) {
			wifiNum = 1
		}
		if (e <= 66 && e > 33) {
			wifiNum = 2
		}
		if (e <= 100 && e > 66) {
			wifiNum = 3
		}
		wifiUrl = 'https://statics.xmcsrv.net/weixin/wifi/wifi' + wifiNum + '.png'
	} else {
		if (e >= 80) {
			wifiNum = 4
		} else if (e >= 60) {
			wifiNum = 3
		} else if (e >= 40) {
			wifiNum = 2
		} else if (e > 0) {
			wifiNum = 1
		} else if (e == 0) {
			wifiNum = 'Error'
		}
		wifiUrl = 'https://statics.xmcsrv.net/weixin/wifi/' + (type == 2 ? 'wifiTwo' + wifiNum : type == 3 ?
			'wifiThree' + wifiNum : '') + '.png'
	}
	return wifiUrl
}

/**
 * 对象按ASCII排序
 * @param data
 * @param order
 * @returns {object}
 */

export function sortByASCII(data, order = 'desc') {
	let obj = {};
	let keys = Object.keys(data).sort((a, b) => {
		switch (order) {
			case 'desc':
				return a.charCodeAt(0) - b.charCodeAt(0);

			case 'asc':
				return b.charCodeAt(0) - a.charCodeAt(0);

			default:
				return b.charCodeAt(0) - a.charCodeAt(0);
		}
	});
	keys.forEach((key) => (obj[key] = data[key]));
	return obj;
}
/**
 * Object转换成XML
 * @param obj
 * @returns {string}
 */

export function simpleObject2Xml(obj) {
	let str = '';
	obj = sortByASCII(obj);
	Object.keys(obj).forEach((key) => (str += `<${key}>${obj[key]}</${key}>`));
	return `<xml>${str}</xml>`;
}
/**
 * XML转换成Object
 * @param str
 * @returns {object}
 */

export function simpleXml2Object(str) {
	let keys = ['appid', 'mch_id', 'device_info', 'nonce_str', 'sign', 'result_code', 'err_code', 'err_code_des',
		'trade_type', 'prepay_id', 'code_url'
	];
	let obj = {};
	let pattern;
	let value;
	keys.forEach((key) => {
		pattern = new RegExp(`<${key}>(.*)</${key}>`);
		value = pattern.exec(str);

		if (value) {
			value = value[1];
			value = value.slice(9, value.length - 3);
			obj[key] = value;
		}
	});
	return obj;
}
/**
 * 对象拼接成字符串
 * @param obj
 * @param trim
 * @returns {string}
 */

export function object2QueryStr(obj = {}, trim = false) {
	let str = '';
	let keys = Object.keys(obj);

	for (let i = 0; i < keys.length; i++) {
		const key = keys[i];

		if (trim) {
			if (obj[key] === null || obj[key] === undefined || obj[key] === '') continue;
		}

		str += `${key}=${obj[key]}&`;
	}

	str = str.substring(0, str.length - 1);
	return str;
}
/**
 * 格式化日期
 * @param date
 * @param fmt
 * @returns {string}
 */

export function date2FmtStr(date, fmt = 'yyyy-MM-dd hh:mm:ss') {
	date = new Date(date);
	let reg;
	const opt = {
		'y+': date.getFullYear().toString(),
		// 年
		'M+': (date.getMonth() + 1).toString(),
		// 月
		'd+': date.getDate().toString(),
		// 日
		'h+': date.getHours().toString(),
		// 时
		'm+': date.getMinutes().toString(),
		// 分
		's+': date.getSeconds().toString() // 秒
		// 有其他格式化字符需求可以继续添加，必须转化成字符串
	};

	for (let k in opt) {
		reg = new RegExp('(' + k + ')').exec(fmt);

		if (reg) {
			fmt = fmt.replace(reg[1], reg[1].length === 1 ? opt[k] : opt[k].padStart(reg[1].length, '0'));
		}
	}
	return fmt;
}
/**
 * 小于10的数补零
 * @param num
 * @returns {string}
 */

function padZero(num) {
	return num < 10 ? '0' + num : num.toString();
}
/**
 * 生成随机字符串
 * @param length 长度
 * @returns {string}
 */

export function getRandomStr(length = 32) {
	const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	const maxPos = chars.length;
	let pwd = '';

	for (let i = 0; i < length; i++) {
		pwd += chars.charAt(Math.floor(Math.random() * maxPos));
	}

	return pwd;
}

export function generateRandomString(length = 16) {
	const characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
	const maxPos = characters.length;
	let result = '';

	for (let i = 0; i < length; i++) {
		result += characters.charAt(Math.floor(Math.random() * maxPos));
	}

	return result;
}
export function decodeURI(data) {
	return JSON.parse(decodeURIComponent(data));
	// return JSON.parse(decodeURIComponent(data.replace(/\+/g, '%20'))); //解析空格显示+号码
}
/**
 * 日期格式化成年月日
 * @param date
 * @returns {void | string | *}
 */

export function date2DateStr(date) {
	return date2FmtStr(date, 'yyyy-MM-dd');
}
/**
 * 日期格式化成年月日时分秒
 * @param date
 * @returns {void | string | *}
 */

export function date2DateTimeStr(date) {
	return date2FmtStr(date, 'yyyy-MM-dd hh:mm:ss');
}
/**
 * 秒数格式化成时长
 * @param ss
 * @returns {string}
 */

export function ss2DurationStr(ss = 0) {
	let hh = '00';
	let mm = '00';

	if (ss <= 0) {
		ss = '00';
	} else if (ss < 60) {
		ss = padZero(ss);
	} else if (ss < 60 * 60) {
		mm = padZero(Math.floor(ss / 60));
		ss = padZero(ss % 60);
	} else {
		hh = padZero(Math.floor(ss / (60 * 60)));
		mm = padZero(Math.floor((ss % (60 * 60)) / 60));
		ss = padZero(Math.floor((ss % (60 * 60)) % 60));
	}

	return `${hh}:${mm}:${ss}`;
}
/**
 * 毫秒数格式化成时长
 * @param ms
 * @returns {string}
 */

export function ms2DurationStr(ms = 0) {
	let ss = Math.floor(ms / 1000);
	return ss2DurationStr(ss);
}
/**
 * 毫秒数格式化成年月日
 * @param ms
 */

export function ms2DateStr(ms) {
	return date2DateStr(new Date(ms));
}
/**
 * 毫秒数格式化成年月日时分秒
 * @param ms
 */

export function ms2DateTimeStr(ms) {
	return date2DateTimeStr(new Date(ms));
}
/**
 * 字节转成B\KB\MB\GB
 * @param byte
 * @returns {string}
 */

export function byteFormat(byte) {
	let size = '';
	if (byte < 0.1 * 1024) size = byte.toFixed(2) + 'B';
	//小于0.1KB，则转化成B
	else if (byte < 0.1 * 1024 * 1024) size = (byte / 1024).toFixed(2) + 'KB';
	//小于0.1MB，则转化成KB
	else if (byte < 0.1 * 1024 * 1024 * 1024) size = (byte / (1024 * 1024)).toFixed(2) + 'MB';
	//小于0.1GB，则转化成MB
	else size = (byte / (1024 * 1024 * 1024)).toFixed(2) + 'GB'; //其他转化成GB

	return size;
}

/**
 * 邮箱正则表达式
 * @param account
 */

export function emailPattern(account) {
	// var reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
	var reg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{3,}$/;
	var ok = reg.test(account);
	return ok
}
/**
 * 手机号正则表达式
 * @param account
 */

export function phonePattern(account) {
	// var reg = /^0?1[3|4|5|6|7|8][0-9]\d{8}$/;
	var reg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/;
	var ok = reg.test(account);
	return ok
}
/**
 * 注册密码正则表达式
 * @param pwd
 */
export function passwordPattern(pwd){
	// /^(?=.*[A-Z])(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*()_\-[\]{}?/.<>,';:-]).{8,64}$/
	var reg= /(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*()_\-[\]{}?/.<>,';:-]).{8,64}$/
	var ok = reg.test(pwd);
	return ok
}

/**
 * 判断数据类型
 * @param obj
 * @returns {string|*}
 */

export function getType(obj) {
	const toString = Object.prototype.toString;
	const map = {
		'[object Boolean]': 'boolean',
		'[object Number]': 'number',
		'[object String]': 'string',
		'[object Function]': 'function',
		'[object Array]': 'array',
		'[object Date]': 'date',
		'[object RegExp]': 'regExp',
		'[object Undefined]': 'undefined',
		'[object Null]': 'null',
		'[object Object]': 'object'
	}; // if (Element && obj instanceof Element) return 'element';

	return map[toString.call(obj)];
}
/**
 * 深拷贝
 * @param data
 * @returns {{}|*}
 */

export function cloneDeep(data) {
	let type = getType(data);
	let obj;
	switch (type) {
		case 'array':
			obj = [];
			for (let i = 0, length = data.length; i < length; i++) {
				obj.push(cloneDeep(data[i]));
			}
			break;
		case 'object':
			obj = {};
			Object.keys(data).forEach((key) => {
				obj[key] = cloneDeep(data[key]);
			});
			break;
		default:
			return data;
	}
	return obj;
}
export function arrUnique(arr, key) {
	let res = [];
	let obj = {};
	for (let i = 0; i < arr.length; i++) {
		if (!obj[arr[i][key]]) {
			res.push(arr[i]);
			obj[arr[i][key]] = true;
		}
	}
	return res;
}
/**
 * 字符串脱敏处理
 *  @param str
 *  @param beginLen
 *  @param endLen
 *  @returns {string}
 */
export function desensitization(str, beginLen, endLen) {
	let len = str.length;
	let firstStr = str.substr(0, beginLen);
	let lastStr = str.substr(endLen);
	let middleStr = str.substring(beginLen, len - Math.abs(endLen)).replace(/[\s\S]/ig, '*');
	let tempStr = firstStr + middleStr + lastStr;
	return tempStr;
}

/**
 * 计算两个日期之间的差值
 *  @param date_1
 *  @param date_2
 *  @returns {string}
 */
export function getDiffDay(date_1, date_2) {
	// 计算两个日期之间的差值
	let totalDays, diffDate
	let myDate_1 = Date.parse(date_1)
	let myDate_2 = Date.parse(date_2)
	// 将两个日期都转换为毫秒格式，然后做差
	diffDate = Math.abs(myDate_1 - myDate_2) // 取相差毫秒数的绝对值

	totalDays = Math.floor(diffDate / (1000 * 3600 * 24)) // 向下取整  
	return totalDays // 相差的天数
}

// ArrayBuffer转16进度字符串示例
export function ab2hex(buffer) {
	const hexArr = Array.prototype.map.call(
		new Uint8Array(buffer),
		function(bit) {
			return ('00' + bit.toString(16)).slice(-2)
		}
	)
	return hexArr.join('')
}
// 字节数组与十六进制互转
export function HexString2Bytes(hexString) {
	var bytes = [];
	for (var i = 0; i < hexString.length - 1; i += 2) {
		bytes.push(parseInt(hexString.substr(i, 2), 16));
	}
	return bytes;
}
// 16进制字符串转buffer
export function hexStringToArrayBuffer(str) {
	var count = str.length / 2;
	if (count.toString().indexOf('.') != -1) {
		count = parseInt(count) + 1 // 有.5就加 1
		count = parseInt(count) // 或者不加
	}
	let buffer = new ArrayBuffer(count);
	let dataView = new DataView(buffer);
	for (var i = 0; i < count; i++) {
		var curCharCode = parseInt(str.substr(i * 2, 2), 16);
		dataView.setUint8(i, curCharCode);
	}
	return buffer;
}

// 16进制转字符串
export function hexToString(str) {
	var val = "",
		len = str.length / 2;
	for (var i = 0; i < len; i++) {
		val += String.fromCharCode(parseInt(str.substr(i * 2, 2), 16));
	}
	return val
}


/**
 *AES解密
 * @param word 解密对象
 * @param key 密钥
 */
export function decryptBase64(word, keyStr) {
	keyStr = keyStr || 'SFpASnVGZW5nMjAy'
	var key = CryptoJS.enc.Utf8.parse(keyStr)
	var decrypt = CryptoJS.AES.decrypt(word, key, {
		mode: CryptoJS.mode.ECB,
		padding: CryptoJS.pad.Pkcs7
	})
	return CryptoJS.enc.Utf8.stringify(decrypt).toString()
}
/**
 * RetCode说明
 * @type {{}}
 */

//RSA加密
export function getRSAEncrypt(publicKey, params) {
	let encrypt = new Encrypt.JSEncrypt()
	encrypt.setPublicKey(publicKey)
	return encrypt.encrypt(params)
}

//随机Key
export function randomKey(number) {
	let key = ''
	let str = '0123456789abcdefghijklmnopqrstuvwxyz'
	for (let i = 0; i < number; i++) {
		let random = Math.random() * str.length
		let number = Math.floor(random)
		let ss = str.substr(number, 1)
		key += ss
	}
	return key
}

/**
 * 当前时间向前推n天
 * @param {*} day 天数
 */
export function getBeforeDay(day) {
	var today = new Date()
	var targetday = today.getTime() + 1000 * 60 * 60 * 24 * day
	today.setTime(targetday)
	var tYear = today.getFullYear()
	var tMonth = today.getMonth()
	var tDate = today.getDate()
	tMonth = doHandMonth(tMonth + 1)
	tDate = doHandMonth(tDate)
	return tYear + "-" + tMonth + "-" + tDate
}

export function doHandMonth(month) {
	var m = month
	if (month.toString().length == 1) {
		m = "0" + month
	}
	return m
}
export function isSocket() {
	return ['ECSKT0003000100Z', 'ECSKT00050001009', 'LTLSE0004000100G', 'ECSWH00100001001', 'ECSWH0006000100A',
		'ECSWH00140001009', 'LTSLT0025000100U', 'ECSKT0012000100Z', 'ECSKT0011000100Y', 'ECSKT0007000100B',
		'ECSKT0005001100A', 'ECSKT00030012009', 'ECSKT00030011000', 'ECSKT1761001700M', 'ECSKT0003001300A',
		'ECSKT0003001400B', 'ECSKT1541001300G', 'ECSKT5128001600M', 'ECSKT0012001400B', 'ECSKT0112001400C',
		'ECSKT02120014008', 'ECSKT0012001300A', 'ECSKT0112001300B', 'ECSKT5460001300J', 'ECSKT1409001800M'
	]
}
export function isDoorLock() {
	return ['HAVLS0008000100F', 'HAVLK00090001009', 'HAVLS00090001007', 'HAVLS0011000100A', 'HABLK0012000100H',
		'HAVLS0013000100C', 'HABLK0013000100I', 'HAVLS00140001008', 'HAVLS00100001009', 'HAVLS0015000100D',
		'HAVLS0016000100E', 'HAVLS0017000100F', 'HAVLS00180001007', 'HAGLK0019000100Q', 'HAVLS137003D900D',
		'HAVLS34220384003', 'HAVLS3380046900X', 'HAVLS0350038400P', 'HAVLS198203D900K', 'HAVLS205403D900D',
		'HAVLS76270384000', 'HAVLS7261041C00B'
	]
}
//判断是否是喂食器
export function isFeeder() {
	return ['HAPFR0022000100T', 'HAPFR0030000100S', 'HAPFRV200000100T', 'HAPFRV300000100U','HAPFRV6500001000']
}
export function debounce(fn, duration = 500) {
	let timer = null;
	return (...arg) => {
		clearTimeout(timer);
		timer = setTimeout(() => {
			fn(...arg);
		}, duration)
	}
}
//分割数组 arr数组  numGroups分割成多少组
export function splitArrayIntoGroups2(arr, numGroups) {
	const groupSize = Math.ceil(arr.length / numGroups); // 每个组的大小
	const result = []; // 存储分割后的组
	let currentGroup = []; // 当前组
	for (let i = 0; i < arr.length; i++) {
		currentGroup.push(arr[i]); // 将元素添加到当前组
		if (currentGroup.length === groupSize) { // 当前组达到平均大小
			result.push(currentGroup); // 将当前组添加到结果数组中
			currentGroup = []; // 创建新的空组
		}
	}
	if (currentGroup.length > 0) {
		result.push(currentGroup); // 将最后一个组添加到结果数组中
	}
	return result;
}
// 版本号对比
export function compareVersions(version1, version2) {
	// 去除版本号中的前缀 "v"
	version1 = version1.replace("v", "");
	version2 = version2.replace("v", "");
	// 拆分版本号和后缀
	const [part1, suffix1] = version1.split("-");
	const [part2, suffix2] = version2.split("-");
	// 比较主版本号
	const mainComparison = compareMainVersions(part1, part2);
	if (mainComparison !== 0) {
		return mainComparison;
	}
	// 如果主版本号相同，比较后缀
	if (suffix1 && !suffix2) {
		return -1; // version1 带有后缀，version2 没有后缀，认为 version1 更大
	} else if (!suffix1 && suffix2) {
		return 1; // version1 没有后缀，version2 带有后缀，认为 version2 更大
	} else if (suffix1 && suffix2) {
		// 如果两个版本号都有后缀，则按字母顺序比较后缀
		return suffix1.localeCompare(suffix2);
	}
	return 0; // 版本号相同
}

function compareMainVersions(version1, version2) {
	// 将版本号拆分为各个部分
	const parts1 = version1.split(".");
	const parts2 = version2.split(".");
	// 逐个比较各个部分的大小
	for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
		const part1 = parseInt(parts1[i] || 0); // 如果某个部分不存在，默认为 0
		const part2 = parseInt(parts2[i] || 0);
		if (part1 > part2) {
			return 1; // version1 大于 version2
		} else if (part1 < part2) {
			return -1; // version1 小于 version2
		}
	}
	// 如果一个版本号的所有部分都相同，但该版本号的部分数量更多，则认为该版本号更大
	if (parts1.length > parts2.length) {
		return 1; // version1 大于 version2
	} else if (parts1.length < parts2.length) {
		return -1; // version1 小于 version2
	}
	return 0; // version1 等于 version2
}

// 分割数组 arr数组  groupSize每组的个数
export function splitArray(array, groupSize) {
	let result = [];
	// 计算数组需要被分成多少组
	let numGroups = Math.ceil(array.length / groupSize);
	// 遍历每一组
	for (let i = 0; i < numGroups; i++) {
		// 使用 slice 方法从原始数组中提取当前组的元素
		let group = array.slice(i * groupSize, (i + 1) * groupSize);
		// 将当前组添加到结果数组中
		result.push(group);
	}
	return result;
}
export function isEmojiCharacter(substring) {
	let iconRule =
		/[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/ig;
	if (iconRule.test(substring)) {
		return true;
	}
	for (var i = 0; i < substring.length; i++) {
		var hs = substring.charCodeAt(i);
		if (0xd800 <= hs && hs <= 0xdbff) {
			if (substring.length > 1) {
				var ls = substring.charCodeAt(i + 1);
				var uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
				if (0x1d000 <= uc && uc <= 0x1f77f) {
					return true;
				}
			}
		} else if (substring.length > 1) {

			var ls = substring.charCodeAt(i + 1);
			if (ls == 0x20e3) {
				return true;
			}
		} else {
			if (0x2100 <= hs && hs <= 0x27ff) {
				return true;
			} else if (0x2B05 <= hs && hs <= 0x2b07) {
				return true;
			} else if (0x2934 <= hs && hs <= 0x2935) {
				return true;
			} else if (0x3297 <= hs && hs <= 0x3299) {
				return true;
			} else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 ||
				hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b ||
				hs == 0x2b50) {
				return true;
			}
		}
	}
}

/**
 * 判断初始化蓝牙状态
 */
export function initTypes(code, errMsg) {
	switch (code) {
		case 10000:
			toast('未初始化蓝牙适配器');
			break;
		case 10001:
			toast('未检测到蓝牙，请打开蓝牙重试！');
			break;
		case 10002:
			toast('没有找到指定设备');
			break;
		case 10003:
			toast('连接失败');
			break;
		case 10004:
			toast('没有找到指定服务');
			break;
		case 10005:
			toast('没有找到指定特征值');
			break;
		case 10006:
			toast('当前连接已断开');
			break;
		case 10007:
			toast('当前特征值不支持此操作');
			break;
		case 10008:
			toast('其余所有系统上报的异常');
			break;
		case 10009:
			toast('Android 系统特有，系统版本低于 4.3 不支持 BLE');
			break;
		case 10012:
			toast('连接超时');
			break;
		case 103:
			toast('请在小程序系统设置中打开蓝牙权限');
			break;
		default:
			if(errMsg == 'openBIuet00thAdapter:fail authorize no response'){
				errMsg = '请在小程序系统设置中打开蓝牙权限'
			}
			toast(errMsg);
	}
}

// 倒计时换算
export function calculateTimeDifference(time, minutes) {
	const currentTime = moment();
	const backendDateTime = moment(time);
	const newDateTime = backendDateTime.clone().add(minutes, 'minutes');
	let timeDifference = newDateTime.diff(currentTime, 'seconds');
	console.log('传过来的时间==',time, currentTime._d,'计算后的时间==',timeDifference)
	if(timeDifference<0 || timeDifference>60){
		timeDifference = 60
	}
	logs({
		info: '门铃来电倒计时秒数',
		time: time,
		currentTime:currentTime._d,
		timeDifference:timeDifference
	})
	return timeDifference
}

// wifi脱敏显示
export function desensitizeWifiName(wifiName) {
	let length = wifiName.length
	if (length === 1) {
		return '*';
	} else if (length === 2) {
		return wifiName[0] + '*';
	} else if (length === 3) {
		return wifiName[0] + '*' + wifiName[2];
	} else if (length === 4) {
		return wifiName[0] + '**' + wifiName[3];
	} else if (length >= 5) {
		const middleIndex = Math.floor(length / 2);
		const startIndex = middleIndex - 1;
		const endIndex = middleIndex + 2;
		const prefix = wifiName.slice(0, startIndex);
		const middle = wifiName.slice(startIndex, endIndex).replace(/./g, '*');
		const suffix = wifiName.slice(endIndex);
		return prefix + middle + suffix;
	}
}

//弹出框封装
function toast(content, showCancel = false) {
	uni.showModal({
		title: '提示',
		content,
		showCancel
	});
}
// 设备状态判断
export function getStatus(status) {
	return status.status === 'online' ?
		(status.wakeUpStatus === '0' ?
			(status.wakeUpEnable === '0' ? 'deep' : 'dormancy') :
			status.wakeUpStatus === '2' ? 'sleeping' : 'online') :
		'OffLine'
};

// 脱敏序列号
export function maskedString(originalString) {
	if (originalString.length > 10) {
		const endIndex = originalString.length - 8;
		const charsToKeep = originalString.slice(0, endIndex);
		const maskedChars = "*".repeat(4);
		const lastFourChars = originalString.slice(-4);
		return charsToKeep + maskedChars + lastFourChars;
	} else {
		return originalString;
	}
}
export function showCloud(item) {
	console.log(item,'云服务')
	// support  false 不支持 true 支持
	// enable   false 未开通 true 开通
	// isExpire false 过期 true使用中
	// expirate 0 过期
	let xmcCssVid = item.xmcCssVid;
	let xmcVoes = item.xmcVoes;
	let pmsVoes = item.pmsVoes;
	let pmsSms = item.pmsSms;
	let netCellular = item.netCellular;
	let list = ['云存储', '云电话', '语音报警', '短信报警', '4G流量']
	let sheetList = [];
	// 使用中
	let icon = ['https://statics.xmcsrv.net/weixin/cloud/icon/xmcCss.png',
		'https://statics.xmcsrv.net/weixin/cloud/icon/xmcVoes.png',
		'https://statics.xmcsrv.net/weixin/cloud/icon/pmsVoes.png',
		'https://statics.xmcsrv.net/weixin/cloud/icon/pmsSms.png',
		'https://statics.xmcsrv.net/weixin/cloud/icon/netCellular.png'
	]
	// 未开通
	let icons = ['https://statics.xmcsrv.net/weixin/device/clouds.png',
		'https://statics.xmcsrv.net/weixin/device/phones.png',
		'https://statics.xmcsrv.net/weixin/cloud/icon/pmsVoes.png',
		'https://statics.xmcsrv.net/weixin/cloud/icon/pmsSms.png',
		'https://statics.xmcsrv.net/weixin/cloud/icon/netCellular.png'
	]
	// 已过期
	let iconpast = ['https://statics.xmcsrv.net/weixin/device/cloudPast.png',
		'https://statics.xmcsrv.net/weixin/device/phonePast.png',
		'https://statics.xmcsrv.net/weixin/cloud/icon/pmsVoes.png',
		'https://statics.xmcsrv.net/weixin/cloud/icon/pmsSms.png',
		'https://statics.xmcsrv.net/weixin/cloud/icon/netCellular.png'
	]
	if (xmcCssVid.support) {
		if (!xmcCssVid.enable) {
			sheetList.push(icons[0])
		} else {
			sheetList.push(xmcCssVid.isExpire ? icon[0] : iconpast[0])
		}
	}
	if (xmcVoes.support) {
		if (!xmcVoes.enable) {
			sheetList.push(icons[1])
		} else {
			sheetList.push(xmcVoes.isExpire ? icon[1] : iconpast[1])
		}
	}
	if (pmsVoes.support) {
		sheetList.push(icon[2])
	}
	if (pmsSms.support) {
		sheetList.push(icon[3])
	}
	if (netCellular.support) {
		sheetList.push(icon[4])
	}
	return sheetList
}
export function AlarmMsgIcon(item) {
	let unlocking = 'https://statics.xmcsrv.net/weixin/unlockingIcon.png';
	let locking = 'https://statics.xmcsrv.net/weixin/locking.png';
	let inform = "https://statics.xmcsrv.net/weixin/inform.png";
	let callPolice = "https://statics.xmcsrv.net/weixin/callPolice.png";
	let telegram = 'https://statics.xmcsrv.net/weixin/telegram.png';
	let messageNotify = 'https://statics.xmcsrv.net/weixin/messageNotify.png';
	let icon;
	if (item.AlarmEvent == 'DoorLockNotify') {
		icon = inform
	} else if (item.AlarmEvent == 'DoorLockCall') {
		icon = telegram
	} else if (item.AlarmEvent == 'DoorLockOpen') {
		icon = unlocking
	} else if (item.AlarmEvent == 'DoorLockClose') {
		icon = locking
	} else if (item.AlarmEvent == 'DoorLockAlarm') {
		icon = callPolice
	} else if (item.AlarmEvent == 'VideoBlind' || item.AlarmEvent == 'PIRAlarm') {
		icon = messageNotify
	} else {
		icon = inform
	}
	return icon
}
export const RetCodeMsg = {
	0: '没有错误',
	100: '成功',
	101: '未知错误(可能引起原因：设备不支持RESTful API，设备不在线,设备登录失效等)',
	102: '版本不支持',
	103: '非法请求',
	104: '用户已登录',
	105: '用户未登录',
	106: '用户名或密码错误',
	107: '无权限',
	108: '超时',
	109: '查找失败，没有找到对应文件',
	110: '查找成功，返回全部文件',
	111: '查找成功，返回部分文件',
	112: '用户已存在',
	113: '用户不存在',
	114: '用户组已存在',
	115: '用户组不存在',
	116: '盗版软件',
	117: '消息格式错误',
	118: '未设置云台协议',
	119: '没有查询到文件',
	120: '配置未启用',
	121: '数字通道未连接',
	122: 'Nat视频链接达到最大，不允许新的Nat视频链接',
	123: 'Tcp视频链接达到最大，不允许新的Tcp视频链接',
	124: '用户名和密码的加密算法错误',
	125: '创建了其它用户，不能再用admin登陆',
	126: 'AES加密数据格式错误',
	127: '用户通过一键遮蔽等功能关闭了视频录像和预览功能',
	130: 'NAS地址已存在',
	131: '路径正在被使用，无法操作',
	132: 'NAS已达到支持的最大值,不允许继续添加',
	140: '消费类产品遥控器绑定按的键错了',
	150: '成功，设备需要重启',
	160: '录像备份失败',
	161: '无录像设备或者设备没在录像',
	162: '设备正在添加过程中',
	202: '设备未登录',
	203: '设备密码错误',
	205: '设备账号错误',
	206: '设备被锁定',
	207: '设备已被拉入黑名单',
	208: '设备被占用',
	602: '需要重启应用程序',
	603: '需要重启系统',
	604: '文件写入出错',
	605: '特性不支持',
	606: '验证失败',
	607: '配置解析出错',
	609: '配置不存在'
};
// 十进制转16进制0x开头字符串
export const turnTenToSixteen=(ten)=>{
	let origin = '0x'+Number(ten).toString(16)
	let end = origin
	if(origin.length===3){
		let arr = origin.split('')
		arr.splice(2,0,'0')
		end = arr.join('')
	}
	return end
}